package ar.vc.trans;

/* Gauss-Jordan by @W!L */

public class GaussJordan
{
    public static  float[] Solve(float[][] A, float[] B, int n)
    {
        int i = 0;
        float p = 1.0f;
        int j;
        int k;

        while ( i < n && p != 0 )
        {
            pivot(A,B,n,i);
            p = A[i][i];

            if ( p != 0)
            {
                for ( j = i; j < n; j++ )
                { A[i][j] /= p; }

                B[i] /= p;

                for ( j = 0; j < n; j++ )
                {
                    if ( j != i )
                    {
                    	float q = A[j][i];

                        for ( k = i; k < n; k++ )
                        {  A[j][k] -= q*A[i][k]; }

                        B[j] -= q*B[i];
                    }
                }
                i += 1;
            }
        }

        if ( p != 0 )
        {
            return B;
        }
        else
        {
        	System.out.println(" Erro #GJ_IMP \n");
        	return null;
        }
    }

    static private void pivot(float[][] A, float[] B, int n, int i)
    {
    	float c = A[i][i];
        int l = i;
        int j;

        for ( j = i + 1; j < n; j++ )
        {
            if ( Math.abs(c) < Math.abs(A[j][i]) )
            {
                c = A[j][i];
                l = j;
            }
        }

        if ( l != i )
        {
            for ( j = 0; j < n; j++ )
            {
                c       = A[l][j];
                A[l][j] = A[i][j];
                A[i][j] = c;
            }
            c    = B[i];
            B[i] = B[l];
            B[l] = c;
        }
    }

}
